import { Session } from '@/utils/storage';
import { UserState } from '@/store/interface/index';
const userStore = defineStore({
	// 这里的id必须为唯一ID
	id: 'userStore',
	state: (): UserState => {
		return {
			userInfo: null as any,
			userId: '',
			userName: '',
			fullName: '',
			userType: '',
			routers: [],
			roles: [],
			systemPrivileges: [] as string[],
			orgIds: [],
			orgId: '',
			openId: '',
			appId: null,
			currentRouter: {},
			defaultSM4Key: '',//默认秘钥
			defaultSM2PublicKey: '',//默认公钥
			defaultSM2PrivateKey: '',//默认私钥
			loginTime:'',//登录时间
			loginIp:'',//登录ip
		};
	},
	// 等同于vuex的getter
	getters: {},
	// pinia 放弃了 mutations 只使用 actions
	actions: {
		// actions可以用async做成异步形式
		// 设置用户信息
		async setUser(userInfo: any) {
			if (!userInfo) {
				Session.remove('USER_INFO');
			}
			this.userInfo = userInfo;
			if (userInfo) {
				if (userInfo.roles) {
					this.roles = userInfo.roles;
				}
				if (userInfo.systemPrivileges) {
					this.systemPrivileges = userInfo.systemPrivileges;
				}
				this.userType = userInfo.userType;
				this.openId = userInfo.openId;
				this.userName = userInfo.userName;
				this.fullName = userInfo.fullName;
				this.userId = userInfo.userId;
				if (userInfo.orgIds) {
					this.orgIds = userInfo.orgIds;
				}
				this.orgId = userInfo.orgId;
				this.appId = userInfo.appId;
			} else {
				this.roles = [];
				this.systemPrivileges = [];
				this.userType = '';
				this.openId = '';
				this.userName = '';
				this.fullName = '';
				this.orgIds = [];
				this.orgId = '';
				this.appId = '';
				this.userId = '';
			}
		},
		async setRouters(routers: any) {
			if (!routers || routers.length <= 0) {
				Session.remove('ROUTERS');
				this.routers = [];
			} else {
				this.routers = routers;
			}
		},
		async setCurrentRouter(router: any) {
			this.currentRouter = router;
		},
		async setUserSecret(secretInfo: any) {
			if (secretInfo) {
				this.defaultSM2PrivateKey=secretInfo.privateKey;
				this.defaultSM2PublicKey=secretInfo.publicKey;
				this.defaultSM4Key=secretInfo.symmetricKey;
			}else{
				this.defaultSM2PrivateKey='';
				this.defaultSM2PublicKey='';
				this.defaultSM4Key='';
			}
		}
	},
	// 开启数据缓存
	persist: {
		enabled: true,
		strategies: [
			{
				// key可以自己定义，不填的话默认就是这个store的ID
				//key: 'user_store',
				// 保存位置，默认保存在sessionStorage storage可以填sessionStorage，localStorage
				storage: sessionStorage,
				// 指定要持久化的数据，默认所有 state 都会进行缓存，你可以通过 paths 指定要持久化的字段，其他的则不会进行持久化。
				//paths: ['userId'],
			},
		],
	},
});
export default userStore;
